//
//  WLScanBindingRouterController.m
//  WanLian
//
//  Created by muzhuang on 2018/9/21.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLScanBindingRouterController.h"
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"
#import "WLTabBarController.h"

@interface WLScanBindingRouterController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) UIView *cameraView;
@property (nonatomic, strong) UIImageView *scanLine;
@property (nonatomic, strong) UIButton *btnAgain;

@end

@implementation WLScanBindingRouterController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"绑定设备";
    
//    self.view.backgroundColor = wlRGBACOLOR(0, 0, 0, 0.5);
//    _cameraView = [[UIView alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-WLScaleX(254))/2.0, (HEIGHT_SCREEN_WL-WLScaleX(254))/2.0, WLScaleX(254), WLScaleX(254))];
    _cameraView = [[UIView alloc] initWithFrame:self.view.bounds];
//    _cameraView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_cameraView];
    // 中间空心洞的区域
    CGRect cutRect = CGRectMake((WIDTH_SCREEN_WL-WLScaleX(254))/2.0, WLScaleX(142), WLScaleX(254), WLScaleX(254));//_cameraView.bounds;//CGRectMake(CGRectGetMidX(frame) - 115, CGRectGetMidY(frame) - 115 - 30, 230, 230);
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:_cameraView.frame];
    // 挖空心洞 显示区域
    UIBezierPath *cutRectPath = [UIBezierPath bezierPathWithRect:cutRect];
//    将circlePath添加到path上
    [path appendPath:cutRectPath];
    path.usesEvenOddFillRule = YES;
    
    CAShapeLayer *fillLayer = [CAShapeLayer layer];
    fillLayer.path = path.CGPath;
    fillLayer.fillRule = kCAFillRuleEvenOdd;
    fillLayer.opacity = 0.5;//透明度
    fillLayer.backgroundColor = [UIColor lightGrayColor].CGColor;
    [self.cameraView.layer addSublayer:fillLayer];
    
    // 边界校准线
    CGFloat cornerWidth = WLScaleX(18);
    CGFloat cornerHeight = WLScaleX(3);
    CGFloat lineWidth = 1;
    // 追加路径
    UIBezierPath *linePath = [UIBezierPath bezierPathWithRect:CGRectMake(cutRect.origin.x, cutRect.origin.y, cornerWidth,cornerHeight)];
    [linePath appendPath:[UIBezierPath bezierPathWithRect:CGRectMake(cutRect.origin.x, cutRect.origin.y,cornerHeight,cornerWidth)]];
    
    [linePath appendPath:[UIBezierPath bezierPathWithRect:CGRectMake(cutRect.origin.x + WLScaleX(254) - cornerWidth , cutRect.origin.y, cornerWidth, cornerHeight)]];
    [linePath appendPath:[UIBezierPath bezierPathWithRect:CGRectMake(cutRect.origin.x + WLScaleX(254) - cornerHeight,  cutRect.origin.y, cornerHeight, cornerWidth)]];
    
    [linePath appendPath:[UIBezierPath bezierPathWithRect:CGRectMake(cutRect.origin.x, cutRect.origin.y + WLScaleX(254) - cornerWidth, cornerHeight,  cornerWidth)]];
    [linePath appendPath:[UIBezierPath bezierPathWithRect:CGRectMake(cutRect.origin.x, cutRect.origin.y + WLScaleX(254) - cornerHeight, cornerWidth, cornerHeight)]];
    
    [linePath appendPath:[UIBezierPath bezierPathWithRect:CGRectMake(cutRect.origin.x + WLScaleX(254) - cornerHeight, cutRect.origin.y + WLScaleX(254) - cornerWidth, cornerHeight, cornerWidth)]];
    [linePath appendPath:[UIBezierPath bezierPathWithRect:CGRectMake(cutRect.origin.x + WLScaleX(254) - cornerWidth, cutRect.origin.y + WLScaleX(254) - cornerHeight, cornerWidth, cornerHeight)]];
    
    CAShapeLayer *pathLayer = [CAShapeLayer layer];
    pathLayer.path = linePath.CGPath;// 从贝塞尔曲线获取到形状
    pathLayer.fillColor = wlUnderlineColor.CGColor; // 闭环填充的颜色
//    pathLayer.lineCap       = kCALineCapSquare;               // 边缘线的类型
//    pathLayer.strokeColor = [UIColor blueColor].CGColor; // 边缘线的颜色
//    pathLayer.lineWidth     = 3.0f;                           // 线条宽度
    [self.cameraView.layer addSublayer:pathLayer];
    
    // 扫描条动画
    _scanLine = [[UIImageView alloc] initWithFrame:CGRectMake(cutRect.origin.x, cutRect.origin.y, cutRect.size.width, lineWidth)];
//    line.image = [[UIImage imageNamed:@"line"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
//    line.tintColor = wlLightTextColor;
    _scanLine.backgroundColor = wlLightTextColor;
    [self.cameraView addSubview:_scanLine];
    
    // 上下游走动画
    CABasicAnimation *animation=[CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    animation.fromValue = @0;
    animation.toValue = [NSNumber numberWithFloat:cutRect.size.height];
    animation.autoreverses = YES;
    animation.duration = 3;
    animation.repeatCount = FLT_MAX;
    [_scanLine.layer addAnimation:animation forKey:nil];
    animation.removedOnCompletion = NO;
//    WLWkSelf
    UILabel *labTip = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(cutRect)+WLScaleX(20), WIDTH_SCREEN_WL-40, 25)];
    labTip.textAlignment = NSTextAlignmentCenter;
    labTip.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labTip.textColor = wlUnderlineColor;
    labTip.text = @"请扫描路由器机身二维码";
    [self.view addSubview:labTip];
    
    _btnAgain = [[UIButton alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-WLScaleX(140))/2.0, CGRectGetMaxY(labTip.frame)+WLScaleX(10), WLScaleX(140), WLScaleX(30))];
    _btnAgain.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:14];
    [_btnAgain setTitle:@"重新扫描" forState:UIControlStateNormal];
    [_btnAgain addTarget:self action:@selector(scanAgainAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnAgain];
    _btnAgain.layer.cornerRadius = 5;
    _btnAgain.layer.borderWidth = WLScaleX(1);
    _btnAgain.layer.borderColor = [UIColor whiteColor].CGColor;
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasFlash] && [device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setFlashMode:AVCaptureFlashModeAuto];
        [device setTorchMode:AVCaptureTorchModeAuto];
        [device unlockForConfiguration];
    }
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    _session = [[AVCaptureSession alloc] init];
    _session.sessionPreset = AVCaptureSessionPresetHigh;
    if ([_session canAddInput:input])
    {
        [_session addInput:input];
    }
    if ([_session canAddOutput:output])
    {
        [_session addOutput:output];
    }
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];

    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = cutRect;
    [self.view.layer insertSublayer:layer atIndex:0];

    [_session startRunning];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    [_session stopRunning];
    [self pauseScanLine];
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects firstObject];
        NSString *stringValue = metadataObject.stringValue;
        WLLog(@"scanout:%@,%@",stringValue,metadataObject);
        [self bindingScanedRouterID:stringValue];
    }
    else
    {
        [self showHUDMessage:@"扫描失败"];
        _btnAgain.hidden = NO;
    }
}

- (void)bindingScanedRouterID:(NSString *)routerid
{
    WLWkSelf
    NSDictionary *paramsp = @{@"macAddress":routerid};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/app/bind" withParamsDic:paramsp success:^(NSDictionary *successDict) {
//        if (weakSelf.bindingSucc) {
//            weakSelf.bindingSucc();
//        }
//        [weakSelf.navigationController popViewControllerAnimated:YES];
//        [weakSelf popToMainController];
        
        [weakSelf queryUserInfo];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        weakSelf.btnAgain.hidden = NO;
//        if (weakSelf.bindingSucc) {
//            weakSelf.bindingSucc();
//        }
//        [weakSelf.navigationController popViewControllerAnimated:YES];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)popToMainController
{
    UIWindow *window =  [[[UIApplication sharedApplication] delegate] window];
    [window showHUDMessage:@"绑定成功"];
    if (_isDismiss) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        [self.navigationController popToRootViewControllerAnimated:NO];
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.wlTabbarController.selectedIndex = 0;
    }
    
}
- (void)queryUserInfo
{
    
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/app/query" withParamsDic:nil success:^(NSDictionary *successDict) {
        WLUserInfo *user = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:user];
        [[WLUseManager shareUser] requestRouterInfo];
        [weakSelf popToMainController];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        weakSelf.btnAgain.hidden = NO;
    } error:^(NSError *error) {
        
    } inView:nil];
}
- (void)pauseScanLine
{
    CFTimeInterval pausedTime = [_scanLine.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    _scanLine.layer.speed = 0.0;
    _scanLine.layer.timeOffset = pausedTime;
}

- (void)resumeScanLine
{
    CFTimeInterval pausedTime = [_scanLine.layer timeOffset];
    _scanLine.layer.speed = 1.0;
    _scanLine.layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [_scanLine.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
//    CFTimeInterval timeSincePause = CACurrentMediaTime() - pausedTime;
//    [_scanLine.layer setTimeOffset:0];
    _scanLine.layer.beginTime = timeSincePause;
}

//static int i = 0;
- (void)scanAgainAction
{
    [self resumeScanLine];
    [_session startRunning];
//    if (i%2==0) {
//        [self pauseScanLine];
//    }
//    else
//    {
//        [self resumeScanLine];
//    }
//    i++;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
